﻿using eLoan.Models;
using System;
using System.Linq;
using System.Web.Mvc;
using WebMatrix.WebData;

namespace eLoan.Controllers
{
    public class UserController : BaseController
    {
        public ActionResult AddEdit(int? id)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.Users);

                var db = new DatabaseContext();

                var userModel = AdministrationHelper.GetUserModel(db, 0);
                userModel.Branches = AdministrationHelper.GetBranchDropDownListByUserRole(db, User.Identity.Name);
                userModel.Roles = AdministrationHelper.GetRoleDropDownList();
                
                if (id == null)
                {
                    userModel.DBCommand = AdministrationHelper.DBCommand.Add.ToString();
                    userModel.User = new User();
                    userModel.User.UserName = string.Empty;
                    userModel.Password = string.Empty;
                    userModel.User.RoleID = (int)AdministrationHelper.Role.User;
                    userModel.User.IsActive = true;

                    return View("AddEdit", userModel);
                }
                else
                {
                    userModel.DBCommand = AdministrationHelper.DBCommand.Edit.ToString();

                    var users = db.Users;
                    var user = users.Where(w => w.ID == id).SingleOrDefault<User>();
                    
                    userModel.User = user;
                    userModel.Password = "******";
                    userModel.UserAccess = AdministrationHelper.GetUserAccess(db, user.UserName);

                    return View("AddEdit", userModel);
                }
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }

        [HttpPost]
        public ActionResult Save(UserModel userModel, string command)
        {
            try
            {
                CheckUserPageAccess(AdministrationHelper.UserPageAccess.Users);

                if (ModelState.IsValid)
                {
                    var db = new DatabaseContext();
                                        
                    if (command == AdministrationHelper.DBCommand.Add.ToString())
                    {
                        if (!WebSecurity.Initialized)
                            WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                        WebSecurity.CreateUserAndAccount(userModel.User.UserName, userModel.Password);

                        db.Users.Add(userModel.User);
                        db = AddNewUserAccess(db, userModel);
                           
                        db.SaveChanges();
                        
                    }
                    else if (command == AdministrationHelper.DBCommand.Edit.ToString())
                    {
                        db.Entry(userModel.User).State = System.Data.EntityState.Modified;
                        db = RemoveOldUserAccess(db, userModel);
                        db = AddNewUserAccess(db, userModel);
                        db.SaveChanges();
                    }
                    else
                    {
                        // cancelled
                    }

                    db.Dispose();
                    
                }

                return RedirectToAction("Users", "Administration");
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }

        private DatabaseContext AddNewUserAccess(DatabaseContext db, UserModel userModel)
        {
            #region Administration
            if (userModel.UserAccess.HasUsersAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Users,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasBranchesAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Branches,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasBanksAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Banks,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasAgentsAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Agents,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasLoanTypesAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.LoanTypes,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasChargeTypesAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ChargeTypes,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasPaymentTypesAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.PaymentTypes,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasNotificationsAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Notifications,
                    UserName = userModel.User.UserName
                });
            }

            #endregion

            #region Masterfile

            if (userModel.UserAccess.HasAddressBookAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.AddressBook,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasProspectsAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Prospects,
                    UserName = userModel.User.UserName
                });
            }

            #endregion

            #region Funding

            if (userModel.UserAccess.HasLoansAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.Loans,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasCancelLoanAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.CancelLoan,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasPrintChequeAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.PrintCheque,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasPrintContractAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.PrintContract,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasReleaseToBranchAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ReleaseToBranch,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasReleaseToCustomerAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ReleaseToCustomer,
                    UserName = userModel.User.UserName
                });
            }

            #endregion

            #region Workspace

            if (userModel.UserAccess.HasLoanPaymentAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.LoanPayment,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasChequeClearingAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ChequeClearing,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasLoanPenaltyAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.LoanPenalty,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasVoidLoanPaymentAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.VoidLoanPayment,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasRequestCloseLoanAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.RequestCloseLoan,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasCloseLoanAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.CloseLoan,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasLoanNotificationAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.LoanNotification,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasDailyCollectionReconciliationAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.DailyCollectionReconciliation,
                    UserName = userModel.User.UserName
                });
            }

            #endregion

            #region Reports

            if (userModel.UserAccess.HasAgentItineraryAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.AgentItinerary,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasCollectionReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.CollectionReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasSalesReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.SalesReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasChequeReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ChequeReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasSavingsReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.SavingsReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasSOAAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.StatementOfAccount,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasPenaltyHistoryAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.PenaltyHistory,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasClosedLoansReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.ClosedLoansReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasDuePaymentsAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.DuePayments,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasDailyCollectionReconciliationReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.DailyCollectionReconciliationReport,
                    UserName = userModel.User.UserName
                });
            }

            if (userModel.UserAccess.HasAgingReportAccess)
            {
                db.UserPageAccess.Add(new UserPageAccess()
                {
                    PageID = (int)AdministrationHelper.UserPageAccess.AgingReport,
                    UserName = userModel.User.UserName
                });
            }
            #endregion

            return db;
        }

        private DatabaseContext RemoveOldUserAccess(DatabaseContext db, UserModel userModel)
        {
            var access = db.UserPageAccess.Where(w => w.UserName == userModel.User.UserName);
            foreach (var acc in access)
            {
                db.UserPageAccess.Remove(acc);
            }

            return db;
        }

        
    }
}
